import numpy as np
from scipy.optimize import minimize

# 约束
def constraint_sum(x):
    return np.sum(x) - 1

def constraint_PAPB(x):
    return x[0] + x[1] - 0.3

def constraint_PAPC(x):
    return x[0] + x[2] - 0.5

# 熵的负数（因为minimize是最小化）
def neg_entropy(x):
    # 避免log(0)，加极小值
    x = np.clip(x, 1e-12, 1)
    return np.sum(x * np.log(x))

cons = [
    {'type': 'eq', 'fun': constraint_sum},
    {'type': 'eq', 'fun': constraint_PAPB},
    {'type': 'eq', 'fun': constraint_PAPC},
]
bounds = [(0, 1)] * 5

# 初始猜测
x0 = np.array([0.1, 0.2, 0.4, 0.15, 0.15])

# 求解
res = minimize(neg_entropy, x0, bounds=bounds, constraints=cons)

# 输出结果
if not res.success:
    print("求解失败：", res.message)
else:
    PA, PB, PC, PD, PE = res.x
    print(f"PA={PA:.6f}, PB={PB:.6f}, PC={PC:.6f}, PD={PD:.6f}, PE={PE:.6f}")
    print("和为：", PA + PB + PC + PD + PE)
    print("最大熵：", -neg_entropy(res.x))
